<template>
  <!-- 添加或修改商家促销活动对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="活动名称" prop="activityName">
        <el-input v-model="form.activityName" placeholder="请输入活动名称"/>
      </el-form-item>
      <el-form-item label="活动时间" prop="startTime">
        <el-date-picker v-model="timeRange" @change="chooseGroundTime" type="datetimerange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动类型" prop="type">
        <el-radio-group v-model="form.type" @change="changeActivityType">
          <el-radio label="1">满立减</el-radio>
          <el-radio label="2">满件折</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否累加" prop="accumulation">
        <el-radio-group v-model="form.accumulation" @change="changeAccumulation">
          <el-radio label="0">不累加</el-radio>
          <el-radio label="1">累加</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 满立减 -->
      <div v-if="form.type=='1'">
        <div class="mt20" v-for="(item,index) in form.activityDetail" :key="index">
          <el-form-item :label=" form.accumulation=='0'?'条件梯度'+ (index + 1):'梯度条件'" prop="activityDetail">
            <el-form-item label="单笔订单金额大于等于" :prop="item.criteria.value" label-width="180px">
              <el-input v-model="item.criteria.value" placeholder="请输入">
                <template slot="append">CNY</template>
              </el-input>
            </el-form-item>
            <el-form-item class="mt10" label="立减" label-width="180px" :prop="item.offering.value">
              <el-input v-model="item.offering.value" placeholder="请输入">
                <template slot="append">CNY</template>
              </el-input>
            </el-form-item>
          </el-form-item>
        </div>
      </div>
      <!-- 满件折 -->
      <div v-if="form.type=='2'">
        <div class="mt20" v-for="(item,index) in form.activityDetail" :key="index">
          <el-form-item :label=" form.accumulation=='0'?'条件梯度'+ (index + 1):'梯度条件'" prop="activityDetail">
            <el-form-item label="单笔订单件数大于等于" :prop="item.criteria.value" label-width="180px">
              <el-input v-model="item.criteria.value" placeholder="请输入">
              </el-input>
            </el-form-item>
            <el-form-item class="mt10" label="折扣" label-width="180px" :prop="item.offering.value">
              <el-input v-model="item.offering.value" placeholder="请输入">
                <template slot="append"> % off 即 折</template>
              </el-input>
            </el-form-item>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer flex-between">
      <div v-if="form.accumulation=='0'">
        <el-button type="success" size="mini" plain @click="addGradient">新增梯度</el-button>
        <el-button type="danger" size="mini" plain @click="cutGradient">删除梯度</el-button>
      </div>
      <div>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  updateSellerStorePromotionActivity
} from "@/api/marketActivity/marketActivity";
import {saveConfig, queryProjectById} from "@/api/autoOperation/fullReduction"
import {parseTime} from "@/utils/ruoyi";

export default {
  name: "FullReduction",
  props: {
    storeId: {
      type: String,
      default: ''
    },
    configId: { //配置id
      type: String,
      default: ""
    },
    userId: { // 绑定店铺的用户id
      type: String,
      default: ""
    },
    isUseShareCode: { // 是否使用分享码
      type: String,
      default: "0"
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 弹出层标题
      title: "新增满减配置",
      // 是否显示弹出层
      open: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityName: [{required: true, message: "活动名称不能为空", trigger: "blur"}],
        type: [{required: true, message: "请选择活动类型", trigger: "blur"}],
        accumulation: [{required: true, message: "请选择是否累加", trigger: "change"}],
        startTime: [{required: true, message: "请选择活动时间", trigger: "change"}],
        activityDetail: [{required: false, message: "开始时间不能为空", trigger: "blur"}],
      },
      storeList: [],//店铺列表
      timeRange: [],// 时间范围
      gradient1: {//满立减梯度数据
        criteria: {type: "amount", value: ""},
        offering: {type: "decreaaeMoney", value: ""}
      },
      gradient2: {//满件折梯度数据
        criteria: {type: "quantity", value: ""},
        offering: {type: "discount", value: ""}
      },
    };
  },
  created() {
    if (this.configId) {
      this.getConfigDetail()
    } else {
      this.reset()
    }
  },
  methods: {
    // 新增梯度
    addGradient() {
      if (this.form.type == '1') {//满立减
        if (this.form.activityDetail.length >= 3) {
          this.$message.error('已经达到梯度数量上限！')
          return
        } else {
          this.form.activityDetail.push(this.gradient1)
        }
      } else {//满件折
        if (this.form.activityDetail.length >= 3) {
          this.$message.error('已经达到梯度数量上限！')
          return
        } else {
          this.form.activityDetail.push(this.gradient2)
        }
      }
    },
    // 减少梯度
    cutGradient() {
      if (this.form.activityDetail.length <= 1) {
        this.$message.error('请至少保留一条梯度！')
        return
      } else {
        this.form.activityDetail.pop()
      }
    },
    // 选择时间
    chooseGroundTime(e) {
      this.form.startTime = new Date(e[0]).getTime()
      this.form.endTime = new Date(e[1]).getTime()
    },
    // 选择活动类型
    changeActivityType(e) {

    },
    // 选择是否累加
    changeAccumulation(e) {
      if (e == '0') { //不累加
        if (this.form.type == '1') { //满立减
          this.form.activityDetail = [this.gradient1]
        } else {//满件折
          this.form.activityDetail = [this.gradient2]
        }
      } else if (e == '1') { //累加
        if (this.form.type == '1') {
          this.form.activityDetail = [this.gradient1]
        } else {
          this.form.activityDetail = [this.gradient2]
        }
      }
    },
    // 获取满减配置详情
    getConfigDetail() {
      this.title = "修改满减配置";
      queryProjectById({id: this.configId}).then(res => {
        let data = res.data
        for (let key in data) { //将所有字符转成字符串
          if (data[key] != null) {
            data[key] = '' + data[key]
          }
        }
        this.form = data
        let startTime = this.parseTime(data.startTime)
        let endTime = this.parseTime(data.endTime)
        this.timeRange.push(startTime, endTime)
        this.form.activityDetail = JSON.parse(data.activityDetail)
      })
    },
    // 取消
    cancel() {
      this.$emit('close', false)
    },
    // 表单重置
    reset() {
      this.form = {
        type: "1",
        accumulation: "0",
        storeId: this.storeId,
        create_by: this.$store.getters.userId,
        activityDetail: [this.gradient1],
        activityName: undefined,
        endTime: undefined,
        startTime: undefined,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          const data = this.form.activityDetail
          this.form.activityDetail = JSON.stringify(data)
          this.form.activityId = this.isUseShareCode == '1' ? undefined : this.form.activityId;
          if (this.form.activityId != null) {
            updateSellerStorePromotionActivity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            saveConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.cancel()
              this.buttonLoading = false;
            });
          }
        }
      });
    },
  }
}
;
</script>
